package com.homedo.core.common.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShortUrlHelper {
	
	private static final Logger log = LoggerFactory.getLogger(ShortUrlHelper.class);
	
	/**
	 * 新浪转换短链接
	 * @param url
	 * @return
	 */
	@SuppressWarnings("unchecked")
    public static String convertToSINAShortUrl(String url) {
        //api地址
        String address = "http://api.t.sina.com.cn/short_url/shorten.json";
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("source", "2815391962");
        paramMap.put("url_long", url);
        String json = HttpClient.get(address,paramMap);
        
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			resultList = JSONObject.parseObject(json, List.class);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
        if(resultList != null && resultList.size()>0){
        	Map<String, Object> resultMap = resultList.get(0);
        	Object url_short = resultMap.get("url_short");
        	if(url_short != null){
        		return url_short.toString();
        	}
        }
        return "";
    }

    public static void  main(String[] args){
		System.out.println("-------------");//http://t.cn/h5zQl7
		System.out.println(ShortUrlHelper.convertToSINAShortUrl("http://wwww.baidu.com"));
	}
}
